package com.example.demo3network;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Paths;

public class DownloadProgerssActivity extends AppCompatActivity implements View.OnClickListener {

    public static final int INIT_PROGRESS = 0;
    public static final String APK_URL = "http://download.sj.qq.com/upload/connAssitantDownload/upload/MobileAssistant_1.apk";
    public static final String FILE_NAME = "imooc.apk";
    private ProgressBar mProgressBar;
    private Button mDownloadButton;
    private TextView mResultTextView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_download_progress);
        findViews();
        setClickListener();

        setData();


        DownloadHelper.download(APK_URL, "", new DownloadHelper.OnDownloadListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(int code, File file) {

            }

            @Override
            public void onFail(int code, File file, String message) {

            }

            @Override
            public void onProgress(int progress) {

            }
        });
    }

    void findViews() {
        mProgressBar = findViewById(R.id.progressBar);
        mDownloadButton = findViewById(R.id.progressBtn);
        mResultTextView = findViewById(R.id.progressTextView);
    }

    void setClickListener() {
        mProgressBar.setOnClickListener(this);
        mDownloadButton.setOnClickListener(this);
        mResultTextView.setOnClickListener(this);
    }

    private void setData() {
        mProgressBar.setProgress(INIT_PROGRESS);
        mDownloadButton.setText(R.string.click_download);
        mResultTextView.setText("准备下载");
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.progressBtn:
                DownloadAsyncTask asyncTask = new DownloadAsyncTask();
                asyncTask.execute(APK_URL);
                break;
        }
    }

    /**
     * String 入参
     * Integer 进度
     * Boolean 返回值
     */
    public class DownloadAsyncTask extends AsyncTask<String, Integer, Boolean> {
        String mFilePath;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            mDownloadButton.setText(R.string.downloading);
            mResultTextView.setText(R.string.downloading);
            mProgressBar.setProgress(INIT_PROGRESS);
        }

        @Override
        protected Boolean doInBackground(String... params) {
            if (params != null && params.length>0) {
                String apkUrl = params[0];
                try {
                    URL url = new URL(apkUrl);
                    URLConnection urlConnection = url.openConnection();
                    InputStream inputStream = urlConnection.getInputStream();
                    int contentLength = urlConnection.getContentLength();
                    mFilePath = Environment.getExternalStorageDirectory() + File.separator + FILE_NAME;
                    File apkFile = new File(mFilePath);
                    if (apkFile.exists()) {
                        boolean result = apkFile.delete();
                        if (!result) {
                            return false;
                        }
                    }

                    int downloadSize = 0;
                    byte[] bytes = new byte[1024];
                    int length;
                    OutputStream outputStream = null;
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                        outputStream = Files.newOutputStream(Paths.get(mFilePath));
                    }
                    while ((length = inputStream.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, length);
                        downloadSize += length;
                        publishProgress(downloadSize*100/contentLength);
                    }
                    inputStream.close();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            } else {
                return  false;
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            // 执行结果处理
            mDownloadButton.setText(result? "下载完成" : "下载失败");
            mResultTextView.setText(result? "下载完成" + mFilePath : "下载失败");
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            // 收到进度，然后在UI线程中处理
            if  (null != values && values.length > 0) {
                mProgressBar.setProgress(values[0]);
            }
        }
    }

}
